package com.mezz.bones.framework.web.util;

import cn.hutool.core.exceptions.ExceptionUtil;
import cn.hutool.extra.servlet.JakartaServletUtil;
import com.alibaba.fastjson.JSONObject;
import com.mezz.bones.framework.base.domain.enums.ResponseCode;
import com.mezz.bones.framework.base.domain.response.Result;
import com.mezz.bones.framework.base.exception.BaseException;
import com.mezz.bones.framework.web.domain.RequestLog;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
/**
 * @author mezz
 * @date 2022-09-22 16:05
 * @description:
 */
@Slf4j
public class FilterUtils {

  public static void filterHandlerException(RequestLog reqLog, HttpServletResponse response, Exception e) {

    log.error("filterHandlerException error ",e);

    Result<?> result = new Result<>();

    // open模块使用过滤器校验token,可能会有 CustomException
    if(e instanceof BaseException){
        BaseException exception = (BaseException) e;

      if(exception.getCode() != null){
          result.setCode(exception.getCode());
      }
      result.setMessage(exception.getMessage());
      reqLog.setExceptionInfo(exception.getMessage());
      JakartaServletUtil.write(response, JSONObject.toJSONString(result),"application/json;charset=utf-8");

      reqLog.setExceptionInfo(null);
      return;
    }

    //默认500
    result.setCode(ResponseCode.SYS_ERROR.getCode());
    result.setMessage(ResponseCode.SYS_ERROR.getMessage());
    reqLog.setExceptionStack(ExceptionUtil.stacktraceToString(e));
    JakartaServletUtil.write(response,JSONObject.toJSONString(result),"application/json;charset=utf-8");
  }

}
